## Mikael Poul Johannesson
## 2024

## Start matter ------------------------------------------------------

library(here)
library(haven)
library(tidyverse)
library(patchwork)
library(readxl)

## Data

## fo_raw <- readRDS(here::here("data", "fo_raw.rds"))

## qsts <-
##   names(fo_raw) %>%
##   map_dfr(
##     function(x)
##       tibble(
##         var = x,
##         qst = attr(fo_raw[[gsub("_dn$", "", x)]], "label")
##       )
##   )

## saveRDS(qsts, here::here("data", "qsts.rds"))

## labs <-
##   grep("^fg_|^on_", names(fo_raw), value = TRUE) %>%
##   map_dfr(function(x)
##     tibble(
##       var = x,
##       lab = names(attr(fo_raw[[x]], "labels")),
##       val = as.numeric(attr(fo_raw[[x]], "labels"))
##     ))

## saveRDS(labs, here::here("data", "labs.rds"))

fo <- readRDS(here::here("data", "fo.rds")) %>%
  mutate_at(
    vars(fg_kunnskap_1, fg_kunnskap_2, fg_kunnskap_3),
    function(x) 8 - x
  )

qsts <- readRDS(here::here("data", "qsts.rds"))

labs <- readRDS(here::here("data", "labs.rds"))

## Utilities ---------------------------------------------------------

#' Project theme for ggplot2.
#'
#' @importFrom ggplot2 theme element_text element_line margin element_blank
#' @importFrom grid unit
#'
#' @param ... Other arguments passed to \code{theme()}.
#'
#' @export
theme_m <- function(...) {
  theme(
    text = element_text(size = 10,
                        colour = "black"),
    axis.text = element_text(size = 10,
                             colour = "black"),
    axis.title = element_text(size = 10,
                              colour = "black"),
    axis.line = element_line(),
    axis.ticks = element_line(colour = "black"),
    axis.ticks.length = unit(1, "mm"),
    plot.margin = margin(1, 5, 1, 1, "mm"),
    panel.spacing.x = unit(7.5, "mm"),
    panel.spacing.y = unit(2, "mm"),
    panel.background = element_blank(),
    panel.grid.major = element_blank(),
    strip.background = element_blank(),
    strip.text = element_text(size = 9, face = "bold"),
    ## strip.text.y = element_text(angle = 0, face = "bold.italic"),
    strip.text.y = element_blank(),
    legend.background = element_blank(),
    legend.key = element_blank(),
    legend.position = "bottom",
    legend.title = element_text(size = 10, face = "bold"),
    legend.key.height = unit(4, "mm"),
    legend.title.align = .125,
    legend.margin = margin(),
    plot.tag = element_text(size = 11, face = "bold"),
    ...
  )
}


## Estimate DID ------------------------------------------------------


get_qst <- function(x) qsts$qst[qsts$var == gsub("_dn$", "", x)]


get_vals <- function(x) {
  .labs <-
    labs %>%
    filter(
      var == gsub("_dn$", "", x),
      lab != "Vet ikke", lab != "Ingen mening"
    )

  paste0(
    .labs$val[which.min(.labs$val)], " = ",
    .labs$lab[which.min(.labs$val)], "; ",
    .labs$val[which.max(.labs$val)], " = ",
    .labs$lab[which.max(.labs$val)]
  )
}

fg_vars <- grep("fg_", names(fo), value = TRUE)
fg_vars <- fg_vars[!grepl("_org|_full", fg_vars)]
on_vars <- grep("on_", names(fo), value = TRUE)
on_vars <- on_vars[!grepl("_org|_full", on_vars)]


est_post_att <- function(var, var2) {

  .labs <- labs[labs$var == var, ]

  if ("Ingen mening" %in% .labs$lab) {

    .labs$val[.labs$lab == "Ingen mening"]
    .fo <- fo[fo[[var]] != .labs$val[.labs$lab == "Ingen mening"], ]
  } else {
    .fo <- fo
  }

  fit <- lm(
    paste0(var, " ~ post + ", var2, " + post:", var2),
    data = .fo
  ) %>%
    broom::tidy() %>%
    slice(4) %>%
    mutate(
      var = var,
      group = var2,
      qst = get_qst(var),
      vals = get_vals(var)
    )
}


effs <-
  bind_rows(
    fg_vars %>%
      map_dfr(est_post_att, var2 = "fg"),
    on_vars %>%
      map_dfr(est_post_att, var2 = "on")
  )


## Figure 3: Support/oppose use  -------------------------------------


att_open_res <-
  effs %>%
  filter(var %in% c("fg_kjennskap_nav", "fg_kunnskap2", "fg_kjennskap_prv")) %>%
  mutate(var = fct_inorder(var)) %>%
  arrange(var) %>%
  mutate(
    lwr = estimate - (1.96 * std.error),
    upr = estimate + (1.96 * std.error),
    varlab = case_when(
      var == "fg_kjennskap_prv" ~ "Parole",
      var == "fg_kjennskap_nav" ~ "Sick leave dialogue meeting",
      var == "fg_kunnskap2" ~ "Refugee assignment"),
    varlab = lvls_reorder(factor(varlab), c(1, 2, 3))
  ) %>%
  arrange(varlab)

fig_att_open <-
  att_open_res %>%
  ggplot(aes(
    estimate, varlab, xmin = lwr, xmax = upr,
    shape = p.value < .0505)) +
  geom_vline(aes(xintercept = 0), linetype = "dotted") +
  geom_errorbarh(height = 0) +
  geom_point(fill = "white") +
  scale_shape_manual(values = c(19, 21)) +
  scale_x_continuous(
    limits = c(-2, 2),
    breaks = seq(-2, 2, .5),
    expand = c(0, 0)) +
  ## scale_y_discrete(labels = function(x) parse(text = x)) +
  theme_m() +
  theme(legend.position = "none") +
  labs(
    x = "Average Treatment Effect on the Treated (ATT)\nof participating in deliberation",
    y = NULL,
    subtitle = str_wrap("Based on your knowledge, how strongly do you support or oppose the Norwegian goverment (/NAV) opening up the use of algortihms for:", 70),
    caption = c("1: Oppose very strongly  --  7: Support very strongly")) +
  theme(plot.subtitle = element_text(face = "bold"))
fig_att_open

ggsave(
  here::here("output", "fig_3.pdf"),
  fig_att_open,
  width = 7, height = 1.75
)

ggsave(
  here::here("output", "fig_3.png"),
  fig_att_open,
  width = 7, height = 1.75
)

## Figure 4: Knowledge about cases -----------------------------------

att_know_res <-
  effs %>%
  filter(var %in% c("fg_kunnskap_1", "fg_kunnskap_2", "fg_kunnskap_3")) %>%
  mutate(var = fct_inorder(var)) %>%
  arrange(var) %>%
  mutate(
    lwr = estimate - (1.96 * std.error),
    upr = estimate + (1.96 * std.error),
    ## varlab = case_when(
    ##   var == "fg_kunnskap_1" ~ "Machine leaning (ML) and Artifical intelligence (AI)",
    ##   var == "fg_kunnskap_2" ~ "How the Norwegian authorities currently decide where refugees will be settled once they have been granted residence in Norway",
    ##   var == "fg_kunnskap_3" ~ "How NAV currently decides which people on sick leave are to be invited to a dialogue meeting about how they can more easily return to work"),
    varlab = case_when(
      var == "fg_kunnskap_1" ~ "Machine leaning (ML) and Artifical intelligence (AI)",
      var == "fg_kunnskap_2" ~ "Refugee assignment",
      var == "fg_kunnskap_3" ~ "Sick leave dialogue meeting"),
    varlab = lvls_reorder(factor(varlab), c(2, 3, 1))
  ) %>%
  arrange(varlab)

fig_att_know <-
  att_know_res %>%
  ggplot(aes(
    estimate, varlab, xmin = lwr, xmax = upr,
    shape = p.value < .0505)) +
  geom_vline(aes(xintercept = 0), linetype = "dotted") +
  geom_errorbarh(height = 0) +
  geom_point(fill = "white") +
  scale_shape_manual(values = c(19, 21)) +
  scale_x_continuous(
    limits = c(-1.5, 1.5),
    breaks = seq(-1.5, 1.5, .5),
    expand = c(0, 0)) +
  ## scale_y_discrete(labels = function(x) parse(text = x)) +
  theme_m() +
  theme(legend.position = "none") +
  labs(
    x = "Average Treatment Effect on the Treated (ATT)\nof participating in deliberation",
    y = NULL,
    #subtitle = "How well would you say you know the following:",
    caption = c("'How well would you say you know the following'\n1: 'Very good knowledge'  --  5: 'No knowledge at all'")) +
  theme(plot.subtitle = element_text(face = "bold"))
fig_att_know

ggsave(
  here::here("output", "fig_4.pdf"),
  fig_att_know,
  width = 7, height = 1.5
)

ggsave(
  here::here("output", "fig_4.png"),
  fig_att_know,
  width = 7, height = 1.5
)

## END ---------------------------------------------------------------
